package cn.xllyd.service;

import cn.xllyd.doc.User;
import cn.xllyd.repository.UserRepository;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;

    public List<User> search(String keyword){
        QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword, "name","age","address");
        HighlightBuilder hiBuilder=new HighlightBuilder();
        hiBuilder.preTags("<b>");
        hiBuilder.postTags("</b>");
        hiBuilder.field("name");
        hiBuilder.field("age");
        hiBuilder.field("address");
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(queryBuilder).withHighlightBuilder(hiBuilder).build();
        List<User> userList = elasticsearchTemplate.queryForList(searchQuery, User.class);
        return userList;
    }

}